var pomelo = require('pomelo');
var async = require('async');
var logger = require('pomelo-logger').getLogger(__filename);
var channelUtil = require('../../../util/channelUtil');
var mem = pomelo.app.get('memclient');
var dispatcher = require('../../../util/dispatcher');


module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};
var handler = Handler.prototype;

handler.enter = function (playerInfo, session, next) {
    var self = this;
    //var uuid = playerInfo.uuid;
    var player = {};
    var sid = null;

    //1,拉取认证
    var scode = playerInfo.scode;
    var uuid = playerInfo.uid;
    var userId = playerInfo.sid;

    var channel = this.app.get('channelService').getChannel(channelUtil.getGlobalChannelName(), true);
    if (!!channel) {
        channel.add(uuid, getSidByUid(uuid, this.app));
        //console.error("当前的人数 ", channel.getMembers());
    }
    pomelo.app.rpc.interface.interfaceRemote.vertifyUser(session, userId, scode, function (data) {
        console.log(data);
        if (data.isSuccess) {
            //把玩家的数据赋给player
            player.username = data.name;
            player.coins = Number(data.money);
            player.headUrl = data.avatar;
            player.uuid = uuid;
            player.userId = userId;
            player.gender = data.sex;
            player.scode = scode;

            sid = session.frontendId;
            //uuid = userId;
            session.bind(uuid);
            session.set("sid", sid);
            session.set('uid', uuid);
            session.on('closed', function (app, session) {
                onUserLeave(self.app, session, {
                    userName: player.username,
                    money: player.coins,
                    gender: player.gender,
                    uuid: player.uuid
                });
            });
            session.pushAll();
            self.app.rpc.hall.hallRemote.add(session, player, channelUtil.getGlobalChannelName(), function () {
                next(null, {
                    user: {
                        uuid: player.uuid,
                        userId: player.userId,
                        scode: player.scode,
                        userName: player.username ? player.username : '游客',
                        money: player.coins,
                        gender: player.gender,
                        headUrl: player.headUrl ? player.headUrl : ""
                    }
                });
            });
        }
    });
};

//掉线自动重连
handler.reEnter = function (playerInfo, session, next) {
    var self = this;
    //var uuid = playerInfo.uuid;
    var player = {};
    var sid = null;

    //1,拉取认证
    var scode = playerInfo.scode;
    var uuid = playerInfo.uid;
    var userId = playerInfo.sid;
    var channel = this.app.get('channelService').getChannel(channelUtil.getGlobalChannelName(), true);

    //pomelo.app.rpc.interface.interfaceRemote.vertifyUser(session, userId, scode, function (data) {
    //    if (data.isSuccess) {
    //        //把玩家的数据赋给player
            player.username = playerInfo.name;
            player.coins = Number(playerInfo.money);
            player.headUrl = playerInfo.headUrl;
            player.uuid = playerInfo.uuid;
            player.userId = playerInfo.scode;
            player.gender = playerInfo.gender;
            player.scode = scode;
    //
    sid = session.frontendId;
    //uuid = userId;
    session.bind(uuid);
    session.set("sid", sid);
    session.set('uid', uuid);
    session.on('closed', function (app, session) {
        onUserLeave(self.app, session, {
            userName: player.username,
            money: player.coins,
            gender: player.gender,
            uuid: player.uuid
        });
    });
    session.pushAll();

    if (!!channel) {
        var msg = {route: "on_log", data: {log: "somebody0"}};
        channel.pushMessage(msg);
    }
    self.app.rpc.hall.hallRemote.add(session, player, channelUtil.getGlobalChannelName(), function () {

        getMem(player.uuid, function (data) {
            if (!!channel) {
                var msg = {route: "on_log", data: {log: "somebody1", data: data}};
                channel.pushMessage(msg);
            }
            if (data) {
                var serverId = data.serverId;
                var deskName = data.deskName;
                if (serverId) {
                    session.set('serverId', serverId);
                    session.pushAll();
                    pomelo.app.rpc.room.roomRemote.reConnect(session, player, sid, data.deskName, function () {
                        var msg = {route: "on_log", data: {log: "somebody2", data: data}};
                        channel.pushMessage(msg);
                    });
                }
            }
            next(null, {
                user: {
                    uuid: player.uuid,
                    userId: player.userId,
                    scode: player.scode,
                    userName: player.username ? player.username : '游客',
                    money: player.coins,
                    gender: player.gender,
                    headUrl: player.headUrl ? player.headUrl : "",
                    info: data
                }
            });
        });
    });
};
var getMem = function (uuid, cb) {
    mem.get(uuid, function (err, data) {
        console.error('get mem///////////////////////////');
        console.error(data);
        cb(data ? data : null);
    });
};
var onUserLeave = function (app, session, player) {
    if (session) {
        console.log('onUserLeave ', player);
        console.log('\n\n');
        console.log('*****************over******************');
        var sid = app.get('serverId');
        app.rpc.hall.hallRemote.quitHall(session, {player: player}, sid, function () {
            app.rpc.hall.hallRemote.kick(session, player, channelUtil.getGlobalChannelName(), function () {
                var channel = app.get('channelService').getChannel(channelUtil.getGlobalChannelName(), true);
                if (!!channel) {
                    channel.leave(player.uuid, getSidByUid(player.uuid, app));
                    //console.error("当前的人数 ", channel.getMembers());
                }
                //console.log('Ok,退出服务器成功! ');
                //console.log('***************************************');
                //console.log('\n\n');
            });
        });
    }
};
var getSidByUid = function (uid, app) {
    var connector = dispatcher.dispatch(uid, app.getServersByType('connector'));
    if (connector) {
        return connector.id;
    }
    return null;
};